package com.ysd.lis.controller.bac;


import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.controller.pub.BaseController;
import com.ysd.lis.entity.SysInterface;
import com.ysd.lis.entity.SysOrgDepartment;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.bac.*;
import com.ysd.lis.entity.inti.IntInstrGermResult;
import com.ysd.lis.entity.lab.LabMaininfo;
import com.ysd.lis.entity.lab.LabReqMain;
import com.ysd.lis.entity.lab.LabRptGroup;
import com.ysd.lis.entity.lab.LabSampleType;
import com.ysd.lis.mapper.bac.TCaseLogMapper;
import com.ysd.lis.mapper.bac.TCaseTableMapper;
import com.ysd.lis.mapper.bac.TCaseTestResultTableMapper;
import com.ysd.lis.mapper.sys.SysInterfaceMapper;
import com.ysd.lis.request.bac.BacDrugCountVo;
import com.ysd.lis.request.bac.BacTestCountDto;
import com.ysd.lis.request.bac.BacTestCountVo;
import com.ysd.lis.service.bac.BacDrugTestResultService;
import com.ysd.lis.service.bac.BacTestResultService;
import com.ysd.lis.service.lab.LabMaininfoService;
import com.ysd.util.RedisUserManager;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wanghuaixing
 * @since 2024-04-12
 */
@RestController
@RequestMapping("/bac_count")
public class BacCountController extends BaseController {

    @Autowired
    BacTestResultService bacTestResultService;

    @Autowired
    LabMaininfoService labMaininfoService;
    @Autowired
    BacDrugTestResultService drugTestResultService;
    @Autowired
    TCaseTableMapper tCaseTableMapper;
    @Autowired
    SysInterfaceMapper sysInterfaceMapper;
    @Autowired
    TCaseLogMapper tCaseLogMapper;
    @Autowired
    TCaseTestResultTableMapper tCaseTestResultTableMapper;

    @ApiOperation("查询数据")
    @GetMapping("/findBacSpecimenCountDistinct")
    public Result findBacSpecimenCountDistinct(String startTime, String endTime, String rptGroup, String resiPhenCodes, String bacteria, String germType, Integer isDistinct) {
        MPJLambdaWrapper<LabMaininfo> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAll(LabMaininfo.class);
        wrapper.selectAs(BacTestResult::getGermNo, LabMaininfo::getGermNo);
        wrapper.selectAs(LabSampleType::getSampleTypeName, LabMaininfo::getSampleTypeNa);

        // 关联查询
        wrapper.leftJoin(BacTestResult.class, p -> p.eq(LabMaininfo::getRptGroup, BacTestResult::getRptGroup)
                .eq(LabMaininfo::getSampleda, BacTestResult::getSampleda)
                .eq(LabMaininfo::getSampleNo, BacTestResult::getSampleNo)
                .eq(BacTestResult::getDelFlag, 0));
        wrapper.leftJoin(LabSampleType.class, p -> p.eq(LabMaininfo::getSampleType, LabSampleType::getSampleTypeCode));
        wrapper.innerJoin(LabRptGroup.class, p -> p.eq(LabRptGroup::getRptGroup, LabMaininfo::getRptGroup)
                .eq(LabRptGroup::getBusinessType, 20));

        // 条件筛选
        wrapper.eq(LabMaininfo::getDelFlag, 0);
        if (StringUtils.isNotBlank(resiPhenCodes)) {
            wrapper.in(BacTestResult::getResiPhenNo, Arrays.asList(resiPhenCodes.split(",")));
        }
        wrapper.between(StrUtil.isNotEmpty(startTime) && StrUtil.isNotEmpty(endTime),
                LabMaininfo::getSampleda, startTime, endTime);
        wrapper.eq(StrUtil.isNotEmpty(rptGroup), BacTestResult::getRptGroup, rptGroup);
        wrapper.eq(StrUtil.isNotEmpty(bacteria), BacTestResult::getGermNo, bacteria);

        // 获取原始数据
        List<LabMaininfo> list = labMaininfoService.list(wrapper);

        List<LabMaininfo> distinctList;
        if (isDistinct == 1) {
            // 当aa=1时，按patNo+sampleType+germNo去重
            distinctList = list.stream()
                    .filter(item -> item.getPatNo() != null && item.getSampleType() != null)
                    .collect(Collectors.collectingAndThen(
                            Collectors.toMap(
                                    item -> item.getPatNo() + "_" + item.getSampleType() + "_" + item.getGermNo(),
                                    item -> item,
                                    (existing, replacement) -> existing
                            ),
                            map -> new ArrayList<>(map.values())
                    ));
        } else {
            // 否则不去重，使用原始数据
            distinctList = list;
        }

        // 后续分组统计逻辑
        Map<String, List<LabMaininfo>> allData = distinctList.stream()
                .filter(p -> StrUtil.isNotEmpty(p.getSampleTypeNa()))
                .collect(Collectors.groupingBy(LabMaininfo::getSampleTypeNa));

        Map<String, List<LabMaininfo>> yangData = distinctList.stream()
                .filter(p -> StrUtil.isNotEmpty(p.getGermNo()) && StrUtil.isNotEmpty(p.getSampleTypeNa()))
                .collect(Collectors.groupingBy(LabMaininfo::getSampleTypeNa));

        List<Map> returnList = new ArrayList<>();
        for (Map.Entry<String, List<LabMaininfo>> entry : allData.entrySet()) {
            Map map = new HashMap();
            map.put("name", entry.getKey());
            map.put("total", entry.getValue().size());
            map.put("yang", CollectionUtils.isNotEmpty(yangData.get(entry.getKey())) ?
                    yangData.get(entry.getKey()).size() : 0);
            map.put("rate", NumberUtil.formatPercent(
                    (Double.parseDouble(map.get("yang") + "") /
                            Double.parseDouble(entry.getValue().size() + "")),
                    2));
            returnList.add(map);
        }

        return Result.succ(1, "查询成功", returnList);
    }


    @ApiOperation("查询")
    @GetMapping("/findBacSpecimenCount")
    public Result findBacSpecimenCount(String startTime, String endTime, String rptGroup, String resiPhenCodes, String bacteria, String germType) {
        MPJLambdaWrapper<LabMaininfo> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAll(LabMaininfo.class);
        wrapper.selectAs(BacTestResult::getGermNo, LabMaininfo::getGermNo);
        wrapper.selectAs(LabSampleType::getSampleTypeName, LabMaininfo::getSampleTypeNa);
        wrapper.leftJoin(BacTestResult.class, p -> p.eq(LabMaininfo::getRptGroup, BacTestResult::getRptGroup).eq(LabMaininfo::getSampleda, BacTestResult::getSampleda).eq(LabMaininfo::getSampleNo, BacTestResult::getSampleNo).eq(BacTestResult::getDelFlag, 0));
        wrapper.leftJoin(LabSampleType.class, p -> p.eq(LabMaininfo::getSampleType, LabSampleType::getSampleTypeCode));
        wrapper.innerJoin(LabRptGroup.class, p -> p.eq(LabRptGroup::getRptGroup, LabMaininfo::getRptGroup).eq(LabRptGroup::getBusinessType, 20));
        wrapper.eq(LabMaininfo::getDelFlag, 0);
        //细菌添加耐药表型搜索条件
        if (StringUtils.isNotBlank(resiPhenCodes)) {
            wrapper.in(BacTestResult::getResiPhenNo, Arrays.asList(resiPhenCodes.split(",")));
        }
        wrapper.between(StrUtil.isNotEmpty(startTime) && StrUtil.isNotEmpty(endTime), LabMaininfo::getSampleda, startTime, endTime);
        wrapper.eq(StrUtil.isNotEmpty(rptGroup), BacTestResult::getRptGroup, rptGroup);
        wrapper.eq(StrUtil.isNotEmpty(bacteria), BacTestResult::getGermNo, bacteria);
        List<LabMaininfo> list = labMaininfoService.list(wrapper);

        Map<List<Object>, List<LabMaininfo>> groupList = list.stream().collect(Collectors.groupingBy(p -> Collections.singletonList(p.getId())));
        List<LabMaininfo> distinctList = new ArrayList<>();
        for (Map.Entry<List<Object>, List<LabMaininfo>> entry : groupList.entrySet()) {
            List<LabMaininfo> items = entry.getValue();
            List<LabMaininfo> sortedItems = items.stream().filter(item -> StringUtils.isNotBlank(item.getGermNo())).collect(Collectors.toList());
            List<LabMaininfo> ullData = items.stream().filter(item -> StringUtils.isBlank(item.getGermNo())).collect(Collectors.toList());
            sortedItems.addAll(ullData);
            if (CollectionUtils.isNotEmpty(sortedItems)) {
                distinctList.add(sortedItems.get(0));
            }
        }

        Map<String, List<LabMaininfo>> allData = distinctList.stream().filter(p -> StrUtil.isNotEmpty(p.getSampleTypeNa())).collect(Collectors.groupingBy(LabMaininfo::getSampleTypeNa));
        Map<String, List<LabMaininfo>> yangData = distinctList.stream().filter(p -> StrUtil.isNotEmpty(p.getGermNo()) && StrUtil.isNotEmpty(p.getSampleTypeNa())).collect(Collectors.groupingBy(LabMaininfo::getSampleTypeNa));
        List<Map> returnList = new ArrayList<>();
        for (Map.Entry<String, List<LabMaininfo>> entry : allData.entrySet()) {
            Map map = new HashMap();
            map.put("name", entry.getKey());
            map.put("total", entry.getValue().size());
            map.put("yang", CollectionUtils.isNotEmpty(yangData.get(entry.getKey())) ? yangData.get(entry.getKey()).size() : 0);
            map.put("rate", NumberUtil.formatPercent((Double.parseDouble(map.get("yang") + "") / Double.parseDouble(entry.getValue().size() + "")), 2));
            returnList.add(map);
        }
        return Result.succ(1, "查询成功", returnList);
    }

    @GetMapping("/findBacSpecimenDetial")
    public Result findBacSpecimenDetial(String startTime, String endTime, String rptGroup, String sampleTypeName, Integer isDistinct) {
        MPJLambdaWrapper<BacTestResult> mpjLambdaWrapper = new MPJLambdaWrapper<>();
        mpjLambdaWrapper.selectAll(BacTestResult.class)
                .selectAs(LabSampleType::getSampleTypeName, BacTestResult::getSampleTypeName)
                .selectAs(LabMaininfo::getSampleType, BacTestResult::getSampleType)
                .selectAs(LabMaininfo::getPatNo, BacTestResult::getPatNo)
                .innerJoin(LabMaininfo.class, p -> p.eq(BacTestResult::getRptGroup, LabMaininfo::getRptGroup).eq(BacTestResult::getSampleda, LabMaininfo::getSampleda).eq(BacTestResult::getSampleNo, LabMaininfo::getSampleNo))
                .innerJoin(LabRptGroup.class, p -> p.eq(LabRptGroup::getRptGroup, BacTestResult::getRptGroup).eq(LabRptGroup::getBusinessType, 20))
                .leftJoin(LabSampleType.class, p -> p.eq(LabMaininfo::getSampleType, LabSampleType::getSampleTypeCode))
                .eq(BacTestResult::getDelFlag, 0)
                .isNotNull(BacTestResult::getGermNo)
                .eq(LabSampleType::getSampleTypeName, sampleTypeName);

        mpjLambdaWrapper.between(StrUtil.isNotEmpty(startTime) && StrUtil.isNotEmpty(endTime), LabMaininfo::getSampleda, startTime, endTime);
        mpjLambdaWrapper.eq(StrUtil.isNotEmpty(rptGroup), BacTestResult::getRptGroup, rptGroup);

        List<BacTestResult> list = bacTestResultService.list(mpjLambdaWrapper);


        List<BacTestResult> distinctList;
        if (isDistinct == 1) {
            // 当aa=1时，按patNo+sampleType+germNo去重
            distinctList = list.stream()
                    .filter(item -> item.getPatNo() != null && item.getSampleType() != null)
                    .collect(Collectors.collectingAndThen(
                            Collectors.toMap(
                                    item -> item.getPatNo() + "_" + item.getSampleType() + "_" + item.getGermNo(),
                                    item -> item,
                                    (existing, replacement) -> existing
                            ),
                            map -> new ArrayList<>(map.values())
                    ));
        } else {
            // 否则不去重，使用原始数据
            distinctList = list;
        }


        Map<List<String>, List<BacTestResult>> allData = distinctList.stream().collect(Collectors.groupingBy(s -> Arrays.asList(s.getGermNo(), s.getGermNa())));
        List<Map> returnList = new ArrayList<>();
        for (Map.Entry<List<String>, List<BacTestResult>> entry : allData.entrySet()) {
            Map map = new HashMap();
            map.put("code", entry.getKey().get(0));
            map.put("name", entry.getKey().get(1));
            map.put("total", entry.getValue().size());
            map.put("rate", NumberUtil.formatPercent((Double.parseDouble(entry.getValue().size() + "") / Double.parseDouble(distinctList.size() + "")), 2));
            returnList.add(map);
        }
        return Result.succ(1, "查询成功", returnList);
    }


    @ApiOperation("查询")
    @GetMapping("/findBacDeptCount")
    public Result findBacDeptCount(String startTime, String endTime, String rptGroup, String resiPhenCodes, String bacteria, Integer isDistinct) {

        MPJLambdaWrapper<LabMaininfo> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAll(LabMaininfo.class);
        wrapper.selectAs(SysOrgDepartment::getName, LabMaininfo::getReqDeptNa);
        wrapper.selectAs(BacTestResult::getGermNo, LabMaininfo::getGermNo);
        wrapper.selectAs(LabSampleType::getSampleTypeName, LabMaininfo::getSampleTypeNa);
        wrapper.leftJoin(BacTestResult.class, p -> p.eq(LabMaininfo::getRptGroup, BacTestResult::getRptGroup)
                .eq(LabMaininfo::getSampleda, BacTestResult::getSampleda)
                .eq(LabMaininfo::getSampleNo, BacTestResult::getSampleNo)
                .eq(BacTestResult::getDelFlag, 0));
        wrapper.leftJoin(LabSampleType.class, p -> p.eq(LabMaininfo::getSampleType, LabSampleType::getSampleTypeCode));
        wrapper.innerJoin(LabRptGroup.class, p -> p.eq(LabRptGroup::getRptGroup, LabMaininfo::getRptGroup)
                .eq(LabRptGroup::getBusinessType, 20));
        wrapper.leftJoin(SysOrgDepartment.class, p -> p.eq(LabMaininfo::getReqDept, SysOrgDepartment::getCode));
        wrapper.eq(LabMaininfo::getDelFlag, 0);

        // 细菌耐药表型搜索条件
        if (StringUtils.isNotBlank(resiPhenCodes)) {
            wrapper.in(BacTestResult::getResiPhenNo, Arrays.asList(resiPhenCodes.split(",")));
        }
        wrapper.between(StrUtil.isNotEmpty(startTime) && StrUtil.isNotEmpty(endTime),
                LabMaininfo::getSampleda, startTime, endTime);
        wrapper.eq(StrUtil.isNotEmpty(rptGroup), BacTestResult::getRptGroup, rptGroup);
        wrapper.eq(StrUtil.isNotEmpty(bacteria), BacTestResult::getGermNo, bacteria);

        List<LabMaininfo> list = labMaininfoService.list(wrapper);
        list.forEach(a -> {
            if (StrUtil.isEmpty(a.getReqDeptNa())) {
                a.setReqDeptNa("");
            }
        });

        List<LabMaininfo> distinctList;
        if (isDistinct == 1) {
            // 当 isDistinct=1 时，按 sampleType + patNo + germNo 去重
            Map<String, List<LabMaininfo>> distinctByKey = list.stream()
                    .collect(Collectors.groupingBy(
                            item -> item.getSampleType() + "|" + item.getPatNo() + "|" +
                                    (StrUtil.isNotEmpty(item.getGermNo()) ? item.getGermNo() : "")
                    ));

            distinctList = distinctByKey.values().stream()
                    .map(items -> items.get(0)) // 取每个分组的第一条记录
                    .collect(Collectors.toList());
        } else {
            // 当 isDistinct=0 时，不去重，直接使用原始数据
            distinctList = list;
        }

        // 按科室分组统计
        Map<String, List<LabMaininfo>> allData = distinctList.stream()
                .collect(Collectors.groupingBy(LabMaininfo::getReqDeptNa));

        Map<String, List<LabMaininfo>> yangData = distinctList.stream()
                .filter(p -> StrUtil.isNotEmpty(p.getGermNo()))
                .collect(Collectors.groupingBy(LabMaininfo::getReqDeptNa));

        List<Map> returnList = new ArrayList<>();
        for (Map.Entry<String, List<LabMaininfo>> entry : allData.entrySet()) {
            if (StringUtils.isBlank(entry.getKey())) {
                continue;
            }
            Map map = new HashMap();
            map.put("name", entry.getKey());
            map.put("total", entry.getValue().size());
            map.put("yang", CollectionUtils.isNotEmpty(yangData.get(entry.getKey())) ?
                    yangData.get(entry.getKey()).size() : 0);
            map.put("rate", NumberUtil.formatPercent(
                    (Double.parseDouble(map.get("yang") + "") /
                            Double.parseDouble(entry.getValue().size() + "")),
                    2));
            returnList.add(map);
        }

        return Result.succ(1, "查询成功", returnList);
    }

    @GetMapping("/findBacDeptDetial")
    public Result findBacDeptDetial(String startTime, String endTime, String rptGroup, String deptName, Integer isDistinct) {
        MPJLambdaWrapper<BacTestResult> mpjLambdaWrapper = new MPJLambdaWrapper<>();
        mpjLambdaWrapper.selectAll(BacTestResult.class)
                .selectAs(SysOrgDepartment::getName, BacTestResult::getDeptName)
                .selectAs(LabMaininfo::getPatNo, BacTestResult::getPatNo)
                .selectAs(LabMaininfo::getSampleType, BacTestResult::getSampleType)
                .innerJoin(LabMaininfo.class, p -> p.eq(BacTestResult::getRptGroup, LabMaininfo::getRptGroup).eq(BacTestResult::getSampleda, LabMaininfo::getSampleda).eq(BacTestResult::getSampleNo, LabMaininfo::getSampleNo))
                .innerJoin(LabRptGroup.class, p -> p.eq(LabRptGroup::getRptGroup, BacTestResult::getRptGroup).eq(LabRptGroup::getBusinessType, 20))
                .leftJoin(SysOrgDepartment.class, p -> p.eq(LabMaininfo::getReqDept, SysOrgDepartment::getCode))
                .eq(BacTestResult::getDelFlag, 0)
                .isNotNull(BacTestResult::getGermNo)
                .eq(StrUtil.isNotEmpty(deptName), SysOrgDepartment::getName, deptName)
                .eq(StrUtil.isEmpty(deptName), LabMaininfo::getReqDept, "");
        mpjLambdaWrapper.between(StrUtil.isNotEmpty(startTime) && StrUtil.isNotEmpty(endTime), LabMaininfo::getSampleda, startTime, endTime);
        mpjLambdaWrapper.eq(StrUtil.isNotEmpty(rptGroup), BacTestResult::getRptGroup, rptGroup);

        List<BacTestResult> list = bacTestResultService.list(mpjLambdaWrapper);

        List<BacTestResult> distinctList;
        if (isDistinct == 1) {
            // 当aa=1时，按patNo+sampleType+germNo去重
            distinctList = list.stream()
                    .filter(item -> item.getPatNo() != null && item.getSampleType() != null)
                    .collect(Collectors.collectingAndThen(
                            Collectors.toMap(
                                    item -> item.getPatNo() + "_" + item.getSampleType() + "_" + item.getGermNo(),
                                    item -> item,
                                    (existing, replacement) -> existing
                            ),
                            map -> new ArrayList<>(map.values())
                    ));
        } else {
            // 否则不去重，使用原始数据
            distinctList = list;
        }

        Map<List<String>, List<BacTestResult>> allData = distinctList.stream().collect(Collectors.groupingBy(s -> Arrays.asList(s.getGermNo(), s.getGermNa())));
        List<Map> returnList = new ArrayList<>();
        for (Map.Entry<List<String>, List<BacTestResult>> entry : allData.entrySet()) {
            Map map = new HashMap();
            map.put("code", entry.getKey().get(0));
            map.put("name", entry.getKey().get(1));
            map.put("total", entry.getValue().size());
            map.put("rate", NumberUtil.formatPercent((Double.parseDouble(entry.getValue().size() + "") / Double.parseDouble(distinctList.size() + "")), 2));
            returnList.add(map);
        }
        return Result.succ(1, "查询成功", returnList);
    }


    @ApiOperation("耐药表型检出-细菌统计查询")
    @GetMapping("/findBacTestCount")
    public Result findBacTestCount(BacTestCountDto bacTestCountDto) {
        MPJLambdaWrapper<BacTestResult> mpjLambdaWrapper = new MPJLambdaWrapper<>();
        mpjLambdaWrapper.selectAll(BacTestResult.class)
                .distinct()
                .selectAs(BacGermDict::getGermNa, BacTestResult::getGermNa)
                .selectAs(LabMaininfo::getPatNo, BacTestResult::getPatNo)
                .selectAs(LabMaininfo::getSampleType, BacTestResult::getSampleType)
                .innerJoin(LabMaininfo.class, p -> p.eq(BacTestResult::getRptGroup, LabMaininfo::getRptGroup).eq(BacTestResult::getSampleda, LabMaininfo::getSampleda).eq(BacTestResult::getSampleNo, LabMaininfo::getSampleNo))
                .innerJoin(LabRptGroup.class, p -> p.eq(LabRptGroup::getRptGroup, BacTestResult::getRptGroup).eq(LabRptGroup::getBusinessType, 20))
                .leftJoin(BacGermDict.class, p -> p.eq(BacTestResult::getGermNo, BacGermDict::getGermNo))
                .eq(BacTestResult::getDelFlag, 0);
        mpjLambdaWrapper.eq(StrUtil.isNotEmpty(bacTestCountDto.getRptGroup()), BacTestResult::getRptGroup, bacTestCountDto.getRptGroup());
        mpjLambdaWrapper.eq(StrUtil.isNotEmpty(bacTestCountDto.getReqDept()), LabMaininfo::getReqDept, bacTestCountDto.getReqDept());
        mpjLambdaWrapper.in(CollectionUtils.isNotEmpty(bacTestCountDto.getReqDepts()), LabMaininfo::getReqDept, bacTestCountDto.getReqDepts());
        mpjLambdaWrapper.between(StrUtil.isNotEmpty(bacTestCountDto.getStartTime()) && StrUtil.isNotEmpty(bacTestCountDto.getEndTime()), LabMaininfo::getSampleda, bacTestCountDto.getStartTime(), bacTestCountDto.getEndTime());
        mpjLambdaWrapper.eq(StrUtil.isNotEmpty(bacTestCountDto.getSampleType()), LabMaininfo::getSampleType, bacTestCountDto.getSampleType());
        mpjLambdaWrapper.eq(StrUtil.isNotEmpty(bacTestCountDto.getGermType()), BacGermDict::getGermType, bacTestCountDto.getGermType());
        mpjLambdaWrapper.eq(StrUtil.isNotEmpty(bacTestCountDto.getBacteria()), BacGermDict::getGermNo, bacTestCountDto.getBacteria());
        mpjLambdaWrapper.eq(bacTestCountDto.getIsAlarm() == 1, BacTestResult::getIsAlarm, 1);
        mpjLambdaWrapper.isNotNull(BacTestResult::getGermNo);
        if (StringUtils.isNotBlank(bacTestCountDto.getResiPhenCodes())) {
            mpjLambdaWrapper.in(BacTestResult::getResiPhenNo, Arrays.asList(bacTestCountDto.getResiPhenCodes().split(",")));
        }
        List<BacTestResult> list = bacTestResultService.list(mpjLambdaWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return Result.fail("暂无数据");
        }

        if (bacTestCountDto.getIsDistinct() == 1) {
            //list集合根据字段如果patNo、sampleType、germNo相同保留一条
            list = list.stream()
                    .filter(item -> item.getPatNo() != null && item.getSampleType() != null)
                    .collect(Collectors.collectingAndThen(
                            Collectors.toMap(
                                    item -> item.getPatNo() + "_" + item.getSampleType() + "_" + item.getGermNo(),
                                    item -> item,
                                    (existing, replacement) -> existing
                            ),
                            map -> new ArrayList<>(map.values())
                    ));
        }

        //筛选出 耐药的细菌 根据耐药表型进行分组
        List<BacTestResult> germAllList = list.stream().filter(p -> StrUtil.isNotEmpty(p.getGermNo())).collect(Collectors.toList());
        Map<String, List<BacTestResult>> allData = list.stream().collect(Collectors.groupingBy(BacTestResult::getGermNo));
        Map<String, List<BacTestResult>> gremData = list.stream().filter(p -> StrUtil.isNotEmpty(p.getResiPhenNa())).collect(Collectors.groupingBy(BacTestResult::getGermNo));
        //1.耐药检出率是 list集合
        List<BacTestCountVo> bacTestCountVos = new ArrayList<>();
        int id = 1;
        for (Map.Entry<String, List<BacTestResult>> entry : gremData.entrySet()) {
            List<BacTestResult> dates = entry.getValue();
            Map<String, List<BacTestResult>> dataByResiPhenNa = dates.stream().collect(Collectors.groupingBy(BacTestResult::getResiPhenNa));
            for (Map.Entry<String, List<BacTestResult>> resiPhenNa : dataByResiPhenNa.entrySet()) {
                BacTestCountVo bacTestCountVo = new BacTestCountVo();
                bacTestCountVo.setId(id++);
                bacTestCountVo.setGermNo(entry.getKey());
                bacTestCountVo.setGermNa(entry.getValue().get(0).getGermNa());
                //细菌检出数
                bacTestCountVo.setDetGerm(allData.get(entry.getKey()).size() + "");
                //细菌检出率
                bacTestCountVo.setDetRateGerm(NumberUtil.formatPercent((Double.parseDouble(String.valueOf(allData.get(entry.getKey()).size())) / Double.parseDouble(String.valueOf(germAllList.size()))), 2));
                //耐药检出数
                bacTestCountVo.setDetRes(dates.size() + "");
                //耐药耐药率 (耐药的数量/这个细菌的总数)
                int size = allData.get(entry.getKey()).size();
                bacTestCountVo.setDetRateRes(NumberUtil.formatPercent((Double.parseDouble(String.valueOf(dates.size())) / Double.parseDouble(String.valueOf(size))), 2));
                //其中耐药表型
                bacTestCountVo.setResiPhenNa(resiPhenNa.getKey());
                bacTestCountVo.setDetType(resiPhenNa.getValue().size() + "");
                bacTestCountVo.setDetRateType(NumberUtil.formatPercent((Double.parseDouble(String.valueOf(resiPhenNa.getValue().size())) / Double.parseDouble(String.valueOf(size))), 2));
                bacTestCountVos.add(bacTestCountVo);

            }
        }
        //将bacTestCountVos中detGerm 数据进行正序排序
        bacTestCountVos.sort(Comparator.comparingInt(o -> Integer.parseInt(o.getDetGerm())));
        return Result.succ(1, "查询成功", bacTestCountVos);
    }

    @ApiOperation("细菌耐药率-细菌统计查询")
    @GetMapping("/findBacTestCountByGerm")
    public Result findBacTestCountByGerm(BacTestCountDto bacTestCountDto) {
        MPJLambdaWrapper<BacTestResult> mpjLambdaWrapper = new MPJLambdaWrapper<>();
        mpjLambdaWrapper.selectAll(BacTestResult.class)
                .selectAs(BacGermDict::getGermNa, BacTestResult::getGermNa)
                .selectAs(LabSampleType::getSampleTypeName, BacTestResult::getSampleTypeName)
                .selectAs(LabSampleType::getSampleTypeCode, BacTestResult::getSampleType)
                .selectAs(LabMaininfo::getPatNo, BacTestResult::getPatNo)
                .innerJoin(LabMaininfo.class, p -> p.eq(BacTestResult::getRptGroup, LabMaininfo::getRptGroup).eq(BacTestResult::getSampleda, LabMaininfo::getSampleda).eq(BacTestResult::getSampleNo, LabMaininfo::getSampleNo))
                .innerJoin(LabRptGroup.class, p -> p.eq(LabRptGroup::getRptGroup, BacTestResult::getRptGroup).eq(LabRptGroup::getBusinessType, 20))
                .leftJoin(LabSampleType.class, p -> p.eq(LabMaininfo::getSampleType, LabSampleType::getSampleTypeCode))
                .leftJoin(BacGermDict.class, p -> p.eq(BacTestResult::getGermNo, BacGermDict::getGermNo))
                .eq(BacTestResult::getDelFlag, 0);
        mpjLambdaWrapper.eq(StrUtil.isNotEmpty(bacTestCountDto.getRptGroup()), BacTestResult::getRptGroup, bacTestCountDto.getRptGroup());
        mpjLambdaWrapper.eq(StrUtil.isNotEmpty(bacTestCountDto.getReqDept()), LabMaininfo::getReqDept, bacTestCountDto.getReqDept());
        mpjLambdaWrapper.in(CollectionUtils.isNotEmpty(bacTestCountDto.getReqDepts()), LabMaininfo::getReqDept, bacTestCountDto.getReqDepts());
        mpjLambdaWrapper.between(StrUtil.isNotEmpty(bacTestCountDto.getStartTime()) && StrUtil.isNotEmpty(bacTestCountDto.getEndTime()), LabMaininfo::getSampleda, bacTestCountDto.getStartTime(), bacTestCountDto.getEndTime());
        mpjLambdaWrapper.eq(StrUtil.isNotEmpty(bacTestCountDto.getSampleType()), LabMaininfo::getSampleType, bacTestCountDto.getSampleType());
        mpjLambdaWrapper.eq(StrUtil.isNotEmpty(bacTestCountDto.getGermType()), BacGermDict::getGermType, bacTestCountDto.getGermType());
        mpjLambdaWrapper.eq(StrUtil.isNotEmpty(bacTestCountDto.getBacteria()), BacGermDict::getGermNo, bacTestCountDto.getBacteria());
        mpjLambdaWrapper.eq(StrUtil.isNotEmpty(bacTestCountDto.getOrgOrder()), BacGermDict::getOrgOrder, bacTestCountDto.getOrgOrder());
        mpjLambdaWrapper.eq(bacTestCountDto.getIsAlarm() == 1, BacTestResult::getIsAlarm, 1);
        mpjLambdaWrapper.isNotNull(BacTestResult::getGermNo);
        if (StringUtils.isNotBlank(bacTestCountDto.getResiPhenCodes())) {
            mpjLambdaWrapper.in(BacTestResult::getResiPhenNo, Arrays.asList(bacTestCountDto.getResiPhenCodes().split(",")));
        }
        List<BacTestResult> list = bacTestResultService.list(mpjLambdaWrapper);

        if (CollectionUtils.isEmpty(list)) {
            return Result.fail("暂无数据");
        }
        if (bacTestCountDto.getIsDistinct() == 1) {
            // 当aa=1时，按patNo+sampleType+germNo去重
            list = list.stream()
                    .filter(item -> item.getPatNo() != null && item.getSampleType() != null)
                    .collect(Collectors.collectingAndThen(
                            Collectors.toMap(
                                    item -> item.getPatNo() + "_" + item.getSampleType() + "_" + item.getGermNo(),
                                    item -> item,
                                    (existing, replacement) -> existing
                            ),
                            map -> new ArrayList<>(map.values())
                    ));
        }
        //筛选出 耐药的细菌 根据耐药表型进行分组
        Map<String, List<BacTestResult>> allData = list.stream().collect(Collectors.groupingBy(BacTestResult::getGermNo));
        //1.耐药检出率是 list集合
        List<BacTestCountVo> bacTestCountVos = new ArrayList<>();
        for (Map.Entry<String, List<BacTestResult>> entry : allData.entrySet()) {
            List<BacTestResult> dates = entry.getValue();
            BacTestCountVo bacTestCountVo = new BacTestCountVo();
            bacTestCountVo.setGermNo(entry.getKey());
            bacTestCountVo.setGermNa(entry.getValue().get(0).getGermNa());
            //细菌检出数
            bacTestCountVo.setDetGerm(dates.size() + "");
            bacTestCountVo.setDetGermInt(dates.size());
            //细菌检出率
            bacTestCountVo.setDetRateGerm(NumberUtil.formatPercent((Double.parseDouble(String.valueOf(dates.size())) / Double.parseDouble(String.valueOf(list.size()))), 2));
            bacTestCountVos.add(bacTestCountVo);
        }
        //按detGerm转Int排序
        bacTestCountVos = bacTestCountVos.stream().sorted(Comparator.comparing(BacTestCountVo::getDetGermInt).reversed()).collect(Collectors.toList());
        return Result.succ(1, "查询成功", bacTestCountVos);
    }

    @ApiOperation("耐药表型检出-药敏统计查询")
    @GetMapping("/findBacDrugCount")
    public Result findBacDrugCount(BacTestCountDto bacTestCountDto) {
        MPJLambdaWrapper<BacDrugTestResult> mpjLambdaWrapper = new MPJLambdaWrapper<>();
        mpjLambdaWrapper.selectAll(BacDrugTestResult.class)
                .selectAs(BacGermDict::getGermNa, BacDrugTestResult::getGermNa)
                .selectAs(LabSampleType::getSampleTypeName, BacDrugTestResult::getSampleTypeName)
//                .selectAs(LabMaininfo::getSamplingSite, BacTestResult::getSamplingSite)
                .selectAs(LabMaininfo::getSampleType, BacDrugTestResult::getSampleType)
                .selectAs(LabMaininfo::getPatNo, BacDrugTestResult::getPatNo)
                .leftJoin(BacTestResult.class, p -> p.eq(BacTestResult::getRptGroup, BacDrugTestResult::getRptGroup)
                        .eq(BacTestResult::getSampleda, BacDrugTestResult::getSampleda)
                        .eq(BacTestResult::getSampleNo, BacDrugTestResult::getSampleNo)
                        .eq(BacTestResult::getIsolateNum, BacDrugTestResult::getIsolateNum)
                        .eq(BacTestResult::getTestFlowNo, BacDrugTestResult::getTestFlowNo)
                        .eq(BacTestResult::getTestNodeNo, BacDrugTestResult::getTestNodeNo)
                )
                .innerJoin(LabMaininfo.class, p -> p.eq(BacTestResult::getRptGroup, LabMaininfo::getRptGroup).eq(BacTestResult::getSampleda, LabMaininfo::getSampleda).eq(BacTestResult::getSampleNo, LabMaininfo::getSampleNo))
                .innerJoin(LabRptGroup.class, p -> p.eq(LabRptGroup::getRptGroup, BacTestResult::getRptGroup).eq(LabRptGroup::getBusinessType, 20))
                .leftJoin(LabSampleType.class, p -> p.eq(LabMaininfo::getSampleType, LabSampleType::getSampleTypeCode))
                .leftJoin(BacGermDict.class, p -> p.eq(BacTestResult::getGermNo, BacGermDict::getGermNo))
                .eq(BacDrugTestResult::getDelFlag, 0);
        mpjLambdaWrapper.eq(StrUtil.isNotEmpty(bacTestCountDto.getRptGroup()), BacDrugTestResult::getRptGroup, bacTestCountDto.getRptGroup());
        mpjLambdaWrapper.eq(StrUtil.isNotEmpty(bacTestCountDto.getReqDept()), LabMaininfo::getReqDept, bacTestCountDto.getReqDept());
        mpjLambdaWrapper.in(CollectionUtils.isNotEmpty(bacTestCountDto.getReqDepts()), LabMaininfo::getReqDept, bacTestCountDto.getReqDepts());
        mpjLambdaWrapper.between(StrUtil.isNotEmpty(bacTestCountDto.getStartTime()) && StrUtil.isNotEmpty(bacTestCountDto.getEndTime()), BacDrugTestResult::getSampleda, bacTestCountDto.getStartTime(), bacTestCountDto.getEndTime());
        mpjLambdaWrapper.eq(StrUtil.isNotEmpty(bacTestCountDto.getSampleType()), LabMaininfo::getSampleType, bacTestCountDto.getSampleType());
        mpjLambdaWrapper.eq(StrUtil.isNotEmpty(bacTestCountDto.getGermType()), BacGermDict::getGermType, bacTestCountDto.getGermType());
        mpjLambdaWrapper.like(StrUtil.isNotEmpty(bacTestCountDto.getBacteria()), BacGermDict::getGermNa, bacTestCountDto.getBacteria());
        mpjLambdaWrapper.eq(StrUtil.isNotEmpty(bacTestCountDto.getGermNo()), BacDrugTestResult::getGermNo, bacTestCountDto.getGermNo());
        mpjLambdaWrapper.eq(StrUtil.isNotEmpty(bacTestCountDto.getResiPhenNa()), BacTestResult::getResiPhenNa, bacTestCountDto.getResiPhenNa());
        mpjLambdaWrapper.eq(bacTestCountDto.getIsAlarm() == 1, BacTestResult::getIsAlarm, 1);
        mpjLambdaWrapper.eq(BacTestResult::getDelFlag, 0);
        mpjLambdaWrapper.isNotNull(BacTestResult::getGermNo);
        List<BacDrugTestResult> list = drugTestResultService.list(mpjLambdaWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return Result.fail("暂无数据");
        }
        if (bacTestCountDto.getIsDistinct() == 1) {
            //list集合根据字段如果patNo、sampleType、germNo相同保留一条
            list = list.stream()
                    .filter(item -> item.getPatNo() != null && item.getSampleType() != null)
                    .collect(Collectors.collectingAndThen(
                            Collectors.toMap(
                                    item -> item.getPatNo() + "_" + item.getSampleType() + "_" + item.getGermNo(),
                                    item -> item,
                                    (existing, replacement) -> existing
                            ),
                            map -> new ArrayList<>(map.values())
                    ));
        }

        if (bacTestCountDto.getIsDistinct() == 1) {
            // 当aa=1时，按patNo+sampleType+germNo去重
            list = list.stream()
                    .filter(item -> item.getPatNo() != null && item.getSampleType() != null)
                    .collect(Collectors.collectingAndThen(
                            Collectors.toMap(
                                    item -> item.getPatNo() + "_" + item.getSampleType() + "_" + item.getGermNo(),
                                    item -> item,
                                    (existing, replacement) -> existing
                            ),
                            map -> new ArrayList<>(map.values())
                    ));
        }


        Map<String, List<BacDrugTestResult>> allData = list.stream().collect(Collectors.groupingBy(BacDrugTestResult::getAntNo));
        List<BacDrugCountVo> dataList = new ArrayList<>();
        for (Map.Entry<String, List<BacDrugTestResult>> antNo : allData.entrySet()) {
            BacDrugCountVo bacDrugCountVo = new BacDrugCountVo();
            bacDrugCountVo.setAntNo(antNo.getKey());
            bacDrugCountVo.setAntNa(antNo.getValue().get(0).getAntNa());
            List<BacDrugTestResult> valueList = antNo.getValue();
            Map<String, List<BacDrugTestResult>> sensitiveNoData = valueList.stream().filter(p -> StrUtil.isNotEmpty(p.getSensitiveNo())).collect(Collectors.groupingBy(BacDrugTestResult::getSensitiveNo));
            int all = valueList.size();
            int r = CollectionUtils.isEmpty(sensitiveNoData.get("R")) ? 0 : sensitiveNoData.get("R").size();
            String rRate = NumberUtil.formatPercent((Double.parseDouble(String.valueOf(r)) / Double.parseDouble(String.valueOf(all))), 2);
            bacDrugCountVo.setRCount(r);
            bacDrugCountVo.setRRate(rRate);
            int s = CollectionUtils.isEmpty(sensitiveNoData.get("S")) ? 0 : sensitiveNoData.get("S").size();
            String sRate = NumberUtil.formatPercent((Double.parseDouble(String.valueOf(s)) / Double.parseDouble(String.valueOf(all))), 2);
            bacDrugCountVo.setSCount(s);
            bacDrugCountVo.setSRate(sRate);
            int i = CollectionUtils.isEmpty(sensitiveNoData.get("I")) ? 0 : sensitiveNoData.get("I").size();
            String iRate = NumberUtil.formatPercent((Double.parseDouble(String.valueOf(i)) / Double.parseDouble(String.valueOf(all))), 2);
            bacDrugCountVo.setICount(i);
            bacDrugCountVo.setIRate(iRate);
            int other = all - r - s - i;
            bacDrugCountVo.setOtherCount(other + "");
            int pos = CollectionUtils.isEmpty(sensitiveNoData.get("POS")) ? 0 : sensitiveNoData.get("POS").size();
            bacDrugCountVo.setPosCount(pos);
            int neg = CollectionUtils.isEmpty(sensitiveNoData.get("NEG")) ? 0 : sensitiveNoData.get("NEG").size();
            bacDrugCountVo.setNegCount(neg);
            dataList.add(bacDrugCountVo);
        }
        return Result.succ(1, "查询成功", dataList);
    }

    @ApiOperation("药敏上传全国药敏网")
    @GetMapping("/findChinaDrug")
    public Result findChinaDrug(BacTestCountDto bacTestCountDto) {
        LambdaQueryWrapper<TCaseTable> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ge(TCaseTable::getDateOfVisit, bacTestCountDto.getStartTime())
                .le(TCaseTable::getDateOfVisit, bacTestCountDto.getEndTime());
        if (StrUtil.isNotEmpty(bacTestCountDto.getKeyword())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(TCaseTable::getName, bacTestCountDto.getKeyword()).or()
                    .like(TCaseTable::getDiagnosis, bacTestCountDto.getKeyword()).like(TCaseTable::getOrganismName, bacTestCountDto.getKeyword()));
        }
        List<TCaseTable> tCaseTables = tCaseTableMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "查询成功", tCaseTables);
    }

    @ApiOperation("药敏上传全国药敏网")
    @GetMapping("/findChinaDrugResult")
    public Result findChinaDrugResult(BacTestCountDto bacTestCountDto) {
        LambdaQueryWrapper<TCaseTable> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ge(TCaseTable::getDateOfVisit, bacTestCountDto.getStartTime())
                .le(TCaseTable::getDateOfVisit, bacTestCountDto.getEndTime());
        if (StrUtil.isNotEmpty(bacTestCountDto.getKeyword())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(TCaseTable::getName, bacTestCountDto.getKeyword()).or()
                    .like(TCaseTable::getDiagnosis, bacTestCountDto.getKeyword()).like(TCaseTable::getOrganismName, bacTestCountDto.getKeyword()));
        }
        List<TCaseTable> tCaseTables = tCaseTableMapper.selectList(lambdaQueryWrapper);
        List<String> collect = tCaseTables.stream().map(tCaseTable -> tCaseTable.getId()).collect(Collectors.toList());

        LambdaQueryWrapper<TCaseTestResultTable> lambdaQueryWrapper111 = new LambdaQueryWrapper<>();
        if (collect.size() > 0) {
            lambdaQueryWrapper111.in(TCaseTestResultTable::getCaseId, collect);
        } else {
            lambdaQueryWrapper111.eq(TCaseTestResultTable::getCaseId, "");
        }
        List<TCaseTestResultTable> tCaseTestResultTables = tCaseTestResultTableMapper.selectList(lambdaQueryWrapper111);
        return Result.succ(1, "查询成功", tCaseTestResultTables);
    }

    @ApiOperation("药敏上传全国药敏网")
    @PostMapping("/uploadDrugChina")
    public Result uploadDrugChina(@RequestBody BacTestCountDto bacTestCountDto) {
        SysUser sysUser = RedisUserManager.getUser();
        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(collect)) {
            for (String webUrl : collect) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.set("startTime", bacTestCountDto.getStartTime());
                jsonObject.set("endTime", bacTestCountDto.getEndTime());
                jsonObject.set("orgId", sysUser.getOrgId());
                jsonObject.set("username", sysUser.getUsername());
                jsonObject.set("realname", sysUser.getRealname());
                webUrl = webUrl.substring(0, webUrl.lastIndexOf("/"));
                String body = HttpUtil.createPost(webUrl + "/upload/uploadDrugChina").body(JSONUtil.toJsonStr(jsonObject)).contentType("application/json").execute().body();
                JSONObject jsonObject111 = new JSONObject(body);
                JSONObject status = jsonObject111.getJSONObject("status");
                String code = status.get("code").toString();
                if ("400".equals(code)) {
                    return Result.fail(jsonObject111.getStr("data"));
                }
            }
        }
        return Result.succ(1, "上传成功", "");
    }

    @ApiOperation("药敏上传全国药敏网日志")
    @GetMapping("/findChinaDrugLog")
    public Result findChinaDrugLog() {
        List<TCaseLog> tCaseLogs = tCaseLogMapper.selectList(new LambdaQueryWrapper<>());
        return Result.succ(1, "查询成功", tCaseLogs);
    }


    @ApiOperation("阳性标本查询")
    @GetMapping("/findPositiveSample")
    public Result findPositiveSample(BacTestCountDto bacTestCountDto) {
        return bacTestResultService.findPositiveSample(bacTestCountDto);
    }


}

